package com.lsh.util;

import com.lsh.entity.Response;
import org.apache.http.HttpEntity;
import org.apache.http.StatusLine;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author ：LiuShihao
 * @date ：Created in 2020/10/18 5:07 下午
 * @desc ：
 */

@Component
public class HttpClient {
    public static Response doGet(String url){
        // 获得Http客户端
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
//        httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 60000 );
//        httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 6000);

        // 创建Get请求
        HttpGet httpGet = new HttpGet(url);
        //设置请求和传输超时时间
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(3000).setConnectTimeout(3000).build();
        httpGet.setConfig(requestConfig);
        // 响应模型
        CloseableHttpResponse response = null;
        StatusLine statusLine =null;
        String resp = null;
        try {
            // 由客户端执行(发送)Get请求
            response = httpClient.execute(httpGet);
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
             statusLine = response.getStatusLine();
//            System.out.println("响应状态为:" + response.getStatusLine());
            if (responseEntity != null) {
                resp = EntityUtils.toString(responseEntity);
//                System.out.println("响应内容为:" + resp);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if (httpClient != null) {
                httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return new Response(statusLine.toString().substring(9,12),resp);
    }
    public static String doPOST(String Url,String RequestMethod,String data){
            StringBuffer sb = null;
            try {
//            建立连接
                URL url = new URL(Url);
                HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
                httpUrlConn.setDoInput(true);
                httpUrlConn.setDoOutput(true);
//                httpUrlConn.setConnectTimeout(5000);
//                httpUrlConn.setReadTimeout(30000);
                String s = RequestMethod.toUpperCase();
                httpUrlConn.setRequestMethod(s);
                httpUrlConn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
                if ("GET".equalsIgnoreCase(RequestMethod)){
                    httpUrlConn.connect();
                }else {
                    //设置请求头   //设置参数类型是json格式
                    //httpUrlConn.connect();     可要    可不要
                    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(httpUrlConn.getOutputStream(), "UTF-8"));
                    writer.write(data);
                    writer.close();
                    // 获取输入流
                }
                InputStream inputStream = httpUrlConn.getInputStream();
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

                // 读取返回结果
                sb = new StringBuffer();
                String str = null;
                while ((str = bufferedReader.readLine()) != null) {
                    sb.append(str);
                }
                // 释放资源
                bufferedReader.close();
                inputStreamReader.close();
                inputStream.close();
                httpUrlConn.disconnect();
            } catch (Exception e) {
                e.printStackTrace();
            }
//            System.out.println(sb);
            return sb.toString();
        }
}
